(* io.ml - Input/Output manager file
 * Licence: LGPLv3
 * Authors: Franck "kushou" Michea < michea_f@epita.fr >
 *)

(* init de SDL *)
let sdl_init () =
  begin
    ignore (Sdlvideo.set_video_mode 1 1 [`DOUBLEBUF]);
    Sdl.init [`EVERYTHING];
    Sdlevent.enable_events Sdlevent.all_events_mask;
  end

let rec wait_key () =
  let e = Sdlevent.wait_event () in match e with
      Sdlevent.KEYDOWN _ -> ()
    | _ -> wait_key ()

let show img img_ pause =
  (* let img_ = img#get img_t in *)
  let (w,h) = (img#get_width, img#get_height) in
  let () =  ignore (Sdlvideo.set_video_mode w h [`DOUBLEBUF]) in
  let d = Sdlvideo.display_format img_ in
  let display = Sdlvideo.get_video_surface () in
  begin
    flush stdout;
    Sdlvideo.blit_surface d display ();
    Sdlvideo.flip display;
    if pause then wait_key ()
  end

let request_height n =
  let get_nth = function
    | 1 -> "first"
    | 2 -> "second"
    | 3 -> "third"
    | n -> Printf.sprintf "%dth" n in
  let rec get_int () =
    Printf.printf "Please input the %s surface height: " (get_nth (n+1));
    try read_int () with
      | Failure _ -> get_int ()
      |	End_of_file -> 
	begin
	  print_newline ();
	  exit 0
	end
  in get_int ()

let get_step () =
  let rec get_int () =
    Printf.printf "Please input the step : ";
    let n = try read_int () with
      | Failure _ -> get_int ()
      | End_of_file -> 
	begin
	  print_newline ();
	  exit 0
	end
    in if n < 18 then get_int () else n
  in get_int ()

let init () =
  begin
    sdl_init ()
  end

let write_heights img =
  let str = ref "" in
  let f (h, (r,g,b), _) =
    str := Printf.sprintf "%s%d: %d %d %d\n" (!str) h r g b
  in begin
    List.iter f img#get_heights;
    let modes =  [Unix.O_WRONLY; Unix.O_CREAT; Unix.O_TRUNC] in
    let file = Unix.openfile img#get_heights_filename modes 0o644 in
    ignore (Unix.write file (!str) 0 (String.length (!str))); 
    Unix.close file
  end
